/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.knowledge.plans;

import com.environment.Aim;
import com.environment.Percept;
import com.environment.Tile;
import com.knowledge.facts.Condition;
import com.knowledge.facts.EnemyHillFact;
import com.knowledge.facts.Fact;
import com.knowledge.facts.FactRepository;
import com.knowledge.facts.FriendlyAntFact;
import com.knowledge.facts.paths.AttackHillPathFact;
import com.utils.InvalidException;
import com.utils.WeightedDistance;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

@SuppressWarnings("unchecked")
public class AttackHillsPlan extends Plan {


    public AttackHillsPlan() {
        preconditions.add(new Condition(Condition.Op.ASSERT,EnemyHillFact.class));
        preconditions.add(new Condition(Condition.Op.ASSERT,FriendlyAntFact.class));
        
        postconditions.add(new Condition(Condition.Op.CLEAR,EnemyHillFact.class));
    }


    @Override
    public void calculateUtility() {
        List<Fact> hills = new ArrayList(FactRepository.getInstance().getInstances(EnemyHillFact.class));
        Set<FriendlyAntFact> ants = FactRepository.getInstance().getFriendlyAnts();
        
        for (FriendlyAntFact ant: ants) {
            if (hills.isEmpty()) return;
            try {
                Collections.sort(hills,new WeightedDistance(ant.getLocation()));
                Tile target = hills.iterator().next().getLocation();
                
                if (ant.hasReference(AttackHillPathFact.class)) {
                    AttackHillPathFact path = (AttackHillPathFact) ant.getReference(AttackHillPathFact.class);
                    path.setUtility(3*Percept.getInstance().getViewRadius2() - path.getRemainingSteps()*path.getRemainingSteps());
                } else if (ant.getAllReferences().isEmpty()){
                    List<Aim> directions = Percept.getInstance().getDirections(ant.getLocation(), target);

                    AttackHillPathFact path = new AttackHillPathFact(ant.getLocation(),target,directions);
                    path.setUtility(3*Percept.getInstance().getViewRadius2() - path.getRemainingSteps()*path.getRemainingSteps());
                    FactRepository.getInstance().addInstance(path);
                    ant.setReference(path);
                }
                
//                movement.add(new Order(path.getSource(),path.getNextAim()));
            } catch (InvalidException ex) {
//                Logger.getLogger(GotoFoodPlan.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public Set<Condition> getMissingPreconditions() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
    